import React, { Component, PropTypes } from 'react'
import { Button, Icon, message } from 'antd'
import '../styles/File.less'

export default class File extends Component{
	constructor(props) {
	    super(props);
	    this.state = {
	    	file: ''
	    }
	}

	componentWillReceiveProps(nextProps){
    if(nextProps.visible == false){
      this.setState({
				file: ''
			});
			this.refs.file.value = '';
    }
  }

	clear = ()=>{
		this.setState({
			file: ''
		});
		this.refs.file.value = '';
		this.props.onChange('');
	}

	onClick = ()=>{
		this.refs.file.click();
	}

	onChange = ()=>{
		var fileName = this.refs.file.value;
		var { fileType } = this.props;
		if(fileType&&fileName.endsWith(fileType)||!fileType){
			this.setState({
				file: this.refs.file.value
			});
			this.props.onChange(Array.prototype.slice.call(this.refs.file.files)[0]);
		}else{
			message.error(`文件格式错误，请输入${fileType}格式的文件`);
		}
	}

	render(){
		var style1 = {display: 'none'}, style2 = {display: 'none'};
		if(this.state.file){
			style2 = {display: 'block'}
		}else{
			style1 = {display: 'inline-block'}
		}
		return (
			<div className="section-form">
    		<div className="input-file-wrap" style={ style1 }>
    			<div onClick={ this.onClick }>
        		{ this.props.children||<Button type="ghost"><Icon type="upload" /> 选择文件</Button> }
        	</div>
        	<input type="file" className="input-file" ref="file" onChange={this.onChange}/>
        </div>
        <div className="form-value" style={ style2 }>
            <input type="text" className="upload-file-text-input ant-input" value={ this.state.file } disabled="disabled" />
            <span className="close" title="取消" onClick={this.clear}>×</span>
        </div>
			</div>
		)
	}
}

File.propTypes = {
  onChange: PropTypes.func
}
File.defaultProps = {
  onChange: function(){
  	console.log('onChange is null')
  }
};

